/*
* @Author: jiameng15
* @Date: 2020-03-26 22:04:14
* @Last Modified by: jiameng15
* @Last Modified time: 2020-04-14 20:34:20
*/
<template>
  <div>
    <div class="row-header">
      <el-form ref="searchForm" :model="searchForm" label-width="50px" inline>
        <el-form-item label=" " prop="address">
          <el-input size="small" v-model="searchForm.address" style="width: 100%;" clearable placeholder="请输入收货地址"></el-input>
        </el-form-item>
        <el-form-item label=" " prop="receiveName">
          <el-input size="small" v-model="searchForm.receiveName" style="width: 100%;" clearable placeholder="请输入收货人"></el-input>
        </el-form-item>
        <el-form-item label=" " prop="trackNumber">
          <el-input size="small" v-model="searchForm.trackNumber" style="width: 100%;" clearable placeholder="请输入快递单号"></el-input>
        </el-form-item>
        <el-form-item label=" " prop="phoneNumber">
          <el-input size="small" v-model="searchForm.phoneNumber" style="width: 100%;" clearable placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label=" " prop="startDate">
          <el-date-picker
            v-model="startDate"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="发货时间开始日期"
            end-placeholder="发货时间结束日期"
            style="width: 100%"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            clearable
            @change="changeDate"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label=" " label-width="80px" prop="dictStatus">
          <el-select
            size="small"
            placeholder="请选择订单状态"
            style="width: 100%;"
            clearable
            v-model="searchForm.dictStatus"
          >
            <el-option v-for="item in dictTypeOptions" :value="item.id" :label="item.name" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="row-form-btn">
        <el-button type="shenda" size="mini" icon="el-icon-search" @click="beforeinitData">查询</el-button>
        <el-button
          size="mini"
          type="shenda"

          icon="el-icon-refresh-right"
          @click="resetForm('searchForm')"
        >重置
        </el-button>
      </div>
    </div>
    <div class="sd-page-line"></div>
    <div class="row-main">
      <el-button type="shenda" size="mini" @click="initData" icon="el-icon-refresh">刷新数据</el-button>
      <el-button type="shenda" size="mini" icon="" @click="downloadTemplate" icon="el-icon-upload">导入模板下载</el-button>
      <el-button type="shenda" size="mini" icon="" @click="importExcel" icon="el-icon-upload">导入数据</el-button>
      <el-button type="shenda" size="mini" icon="" @click="exportExcel" icon="el-icon-download">导出未处理数据</el-button>
      <input type="file" ref="key" id="fileInput" accept="*" @change="getFile(fileList.excel)" style="display: none">

      <el-table
        :data="tableData" ref="formData" :header-cell-style="{ 'background':$store.state.app.tableBgColor,'color':'#606266' }"
        v-loading.fullscreen="mainTableLoading" element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.2)"
        :default-sort="{prop: 'insertTime', order: 'descending'}" class="row-main-table"
      >
        <el-table-column prop="address" label="收货地址" align="center"></el-table-column>
        <el-table-column prop="receiveName" label="收货人" align="center"></el-table-column>
        <el-table-column prop="trackNumber" label="快递单号" align="center"></el-table-column>
        <el-table-column prop="phoneNumber" label="联系电话" align="center"></el-table-column>
        <el-table-column prop="dictStatusName" label="订单状态" align="center"></el-table-column>
        <el-table-column prop="price" label="支付金额" align="center"></el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
        <el-table-column prop="insertTime" label="下单时间" align="center"></el-table-column>

        <el-table-column label="操作" align="center">
          <template v-slot="{ row, rowIndex }">
            <el-dropdown trigger="click">
              <div>
                <svg-icon class="el-dropdown-link" icon-class="operation"></svg-icon>
              </div>
              <el-dropdown-menu slot="dropdown">
                <el-button class="operation" @click="getExpressinFormationInfoData(row)" v-has="'editBaseInfo'">物流卡列表</el-button>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div :style="{'overflow-x': $store.state.app.screenWidth<992?'scroll':'none'}">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="row-main-pager"
          :current-page.sync="page.current"
          :page-size="page.size"
          :total="page.total"
          layout="total, sizes, prev, pager, next, jumper"
          background></el-pagination>
      </div>
    </div>
    <el-dialog
      class="delete"
      top="33vh"
      :visible.sync="deleteNoticeVisible"
      :append-to-body="true"
      width="30%"
    >
      <span style="display: flex; justify-content: center;">确定删除【<span v-text="deleteRow.realnameName"
                                                                       class="click_text"></span>】实名通道</span>
      <span class="dialog-footer" slot="footer">
        <el-button @click="deleteNoticeVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="deleteNoticeFunc()" size="small">确 定</el-button>
      </span>
    </el-dialog>
    <el-drawer
      class="drawer_form"
      size="80%"
      :title="noticeTitle"
      :visible.sync="drawer"
      direction="ttb"
    >
      <div class="sd-drawer-content notice_drawer_form custom_drawer_content">
        <div class="sd-drawer-content-pannel">
          <el-table
            height="400"
            :data="cardsTable"
            ref="formData"
            :loading="mainTableLoading"
          >
            <el-table-column prop="oldCardNumber" label="旧卡号"></el-table-column>
            <el-table-column prop="newCardNumber" label="新卡号"></el-table-column>
          </el-table>
        </div>
      </div>
      <div class="sd-drawer-footer">
        <div class="buttons">
          <el-button @click="drawer=false" size="small" type="primary">确定</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  getExpressinFormationList, // 获取物流列表
  getExpressinFormationInfo, // 获取物流信息
  // saveRealnameChannel, // 保存实名
  // deleteRealnameChannel, // 删除实名
  importChangeExcel
} from "@/api/getData";
import {getStore, setStore} from "@/config/mUtils";
import {subStringForExceptLetter} from "@/utils/utils";
import Editor from "@/components/Editor";

var qiniu = require("qiniu-js");
var imgUrl = localStorage.getItem("image");
export default {
  name: "StockOut",
  data() {
    return {
      cardsTable: [],
      config: [],
      deleteRow: {},
      // 实名类型下拉选
      dictTypeOptions: [
        {
          id: '',
          name: '请选择订单状态'
        },
        {
          id: 'WAITPAY',
          name: '未支付'
        },
        {
          id: 'PROCESSED',
          name: '已处理'
        },
        {
          id: 'PROCESSING',
          name: '处理中'
        },
        {
          id: 'NOTPROCESSED',
          name: '未处理'
        }
      ],
      // 执行顺序下拉选
      dictOrderOptions: [
        {
          id: 'PRE_RECHARGE',
          name: '充值前'
        },
        {
          id: 'AFTER_RECHARGE',
          name: '充值后'
        }
      ],
      // 自动通过下拉选
      dictIsAutoPassOptions: [
        {
          id: 'C_YES',
          name: '是'
        },
        {
          id: 'C_NO',
          name: '否'
        }
      ],
      dictRechargeButtonOptions: [
        {
          id: 'C_YES',
          name: '是'
        },
        {
          id: 'C_NO',
          name: '否'
        }
      ],
      configList: [
        {
          key: 'dictIdentityPicFront',
          value: '身份证正面',
          disabled: false
        },
        {
          key: 'dictIdentityPicBack',
          value: '身份证背面',
          disabled: false

        },
        {
          key: 'dictIdentityPicInHand',
          value: '手执身份证',
          disabled: false

        },
        {
          key: 'dictCustomerName',
          value: '客户姓名',
          disabled: false

        },
        {
          key: 'dictIdentityNumber',
          value: '身份证号码',
          disabled: false

        },
        {
          key: 'dictPhoneNumber',
          value: '客户手机号',
          disabled: false

        }
      ],
      accountTemplateList: [],
      dictIdentityPicFront: false,
      dictIdentityPicBack: false,
      dictIdentityPicInHand: false,
      dictCustomerName: false,
      dictIdentityNumber: false,
      dictPhoneNumber: false,

      configJson: {
        dictCustomerName: false,
        dictPhoneNumber: false,
        dictIdentityNumber: false,
        dictIdentityPicFront: false,
        dictIdentityPicBack: false,
        dictIdentityPicInHand: false,
      },
      // 图片上传
      upload_qiniu_addr: imgUrl,
      upload_qiniu_url: "https://upload.qbox.me",
      qiniuData: {},
      // 新增、修改-数据对象
      saveInfo: {
        realnameName: '',
        dictType: "",
        url: "",
        config: "",
        dictOrder: "",
        dictRechargeButton: "",
        dictIsAutoPass: "",
        accountValue: {}
      },
      // 抽屉
      noticeTitle: "",
      drawer: false,
      direction: "ttb",

      formData: {
        id: null,
        title: null,
        contentText: null,
        sendNumber: null,
        expirationDate: null,
        dictNoticeType: null
      },
      // ----↓修改公告
      submitLoading: false,
      showEdit: false,
      deleteNoticeVisible: false,
      buttonRetryLoading: false,
      startDate: [],
      endDate: [],
      // 查询条件
      searchForm: {
        address: "", //收货地址
        receiveName: "",// 收货人
        trackNumber: "",       // 快递单号
        phoneNumber: "",      // 联系电话
        remark: "", // 备注
        startTime: '',
        endTime: '',
        dictStatus: ''
      },
      // loading...
      loading: false,
      searchLoading: false,
      mainTableLoading: false,
      // 分页
      page: {
        current: 1,
        size: 10,
        total: 0,
        ascs: [],
        descs: []
      },
      //
      tablePage: {
        pageSize: 15,
        pageSizes: [5, 15, 20, 50, 100, 200, 500, 1000]
      },
      tableData: [],
      value: false,
      tableLoading: false,
      id: "",

      okloading: false,
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      fileList: {
        excel: ""
      },
      formRules: {
        headName: [{required: true, message: "请输入套餐组名称", trigger: "blur"}],
      }
    };
  },
  components: {
    Editor
  },
  watch: {
    user: function (val, oldval) {
      this.form.belongId = val.value;
      this.form.username = val.label;
    }
  },
  created() {
    // 读取session里的查询参数
    let searchObj = sessionStorage.getItem(this.$route.path);
    if (searchObj != undefined && searchObj != null && searchObj != "") {
      this.searchForm = JSON.parse(searchObj);
      if (this.searchForm.startTime !== "") {
        this.startDate.push(this.searchForm.startTime);
      }
      if (this.searchForm.endTime !== "") {
        this.startDate.push(this.searchForm.endTime);
      }
      this.page = this.searchForm.page;
    }
    this.initData();
  },

  methods: {
    // 发布时间区间
    changeDate() {
      // console.log(this.startDate);
      if (this.startDate) {
        this.searchForm.startTime = this.startDate[0];
        this.searchForm.endTime = this.startDate[1];
      } else {
        this.searchForm.startTime = "";
        this.searchForm.endTime = "";
      }
    },
    // 导出所有未处理的excel
    exportExcel() {
      let url = `/api/crm-system/card/exportChangeExcel/white`
      window.location.href = url
    },
    importExcel() {
      document.getElementById("fileInput").click()
    },
    // 选中数组转json
    configArr2Json(arr) {
      arr.map(item => {
        if (item == "dictIdentityPicFront") {
          this.configJson["dictCustomerName"] = true
          this.configJson["dictIdentityNumber"] = true
          this.dictCustomerName = "checked"
          this.dictIdentityNumber = "checked"
        }
        this.configJson[item] = true
      })
      this.saveInfo.config = JSON.stringify(this.configJson)
    },
    // 选中json转数组
    configJson2Arr(json) {
      let arr = []
      for (var key in json) {
        if (json[key] === true) {
          arr.push(`${key}`)
        }
      }
      this.config = arr
    },
    async getExpressinFormationInfoData(row) {
      this.noticeTitle = "物流卡列表";
      this.cardsTable = [];
      const returnData = await getExpressinFormationInfo({id: row.id});
      if (returnData._result) {
        // 数据回显
        returnData.data.cardNumberVOList.map(item => {
          const data = {};
          data.oldCardNumber = item.oldCardNumber;
          data.newCardNumber = item.newCardNumber;
          this.cardsTable.push(data);
        });
        this.drawer = true;
      }
    },
    // 保存-校验
    submitHandle(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.saveNewNoticeFunc();
        } else {
          return false;
        }
      });
    },
    // 保存-接口
    async saveNewNoticeFunc() {
      const returnData = await saveRealnameChannel(this.saveInfo);
      if (returnData._result) {
        this.$message.success("提交成功");
        this.initData();
        this.drawer = false;
      }
    },
    // 删除
    deleteNoticeConfirm(row) {
      // console.log(row);
      this.deleteRow = row
      this.deleteNoticeVisible = true;
    },
    // 删除-接口
    async deleteNoticeFunc() {
      console.log('删除')
      const returnData = await deleteRealnameChannel({
        id: this.deleteRow.id
      });
      if (returnData._result) {
        this.$message.success("提交成功");
        this.deleteNoticeVisible = false;
        this.initData();
      }
    },
    handleCurrentChange(currentPage) {
      this.page.current = currentPage;
      this.initData();
    },
    handleSizeChange(pageSize){
      this.page.current = 1;
      this.page.size = pageSize;
      this.initData()
    },
    // 关闭抽屉
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(_ => {
          console.log(123);
          done();
          this.$refs.saveInfo.clearValidate();
          this.$refs.saveInfo.resetFields();
          // this.saveInfo={
          //   title:'',
          //   contentText:'',
          //   sendNumber:'',
          //   expirationDate:'',
          //   dictNoticeType:'',
          //   clickNumber:'0'
          // }
        })
        .catch(_ => {
        });
    },
    beforeinitData() {
      this.page.current = 1
      this.initData()
    },
    // 初始化-列表
    async initData(theKey) {
      this.mainTableLoading = true;
      this.searchForm.page = this.page;
      // 保存查询参数到session
      sessionStorage.setItem(this.$route.path, JSON.stringify(this.searchForm));
      const returnData = await getExpressinFormationList(this.searchForm, {
        obj: this,
        key: "tableLoading;" + theKey
      });
      this.tableData = [];
      //console.log(returnData)
      if (returnData._result) {
        // 数据回显
        returnData.data.records.map(item => {
          const data = {};
          data.id = item.id;
          data.oemId = item.oemId;
          data.address = item.address;
          data.receiveName = item.receiveName;
          data.trackNumber = item.trackNumber;
          data.phoneNumber = item.phoneNumber;
          data.remark = item.remark !== null ? item.remark.substring(1, item.remark.length - 1) : item.remark;
          data.dictStatus = item.dictStatus;
          data.dictStatusName = item.dictStatusName;
          data.price = item.price;
          data.endTime = item.endTime;
          data.insertTime = item.insertTime;
          this.tableData.push(data);
        });
        this.tableLoading = false;
        this.page.total = returnData.data.total;
      }
      this.mainTableLoading = false;
    },
    // 重置-查询条件
    resetForm(formName) {
      // this.$refs[formName].resetFields();
      this.startDate = "";
      this.searchForm = {
        address: "", //收货地址
        receiveName: "",// 收货人
        trackNumber: "",       // 快递单号
        phoneNumber: "",      // 联系电话
        remark: "", // 备注
        startTime: '',
        endTime: '',
        dictStatus: ''
      };
    },

    selectAccountTemplate(e) {
      this.accountTemplateList = []
      console.log(e)
      let template
      if (this.dictTypeOptions.length > 0) {
        template = JSON.parse(this.dictTypeOptions[e - 1].accountTemplate)
      }
      for (const key in template) {
        if (template.hasOwnProperty(key)) {
          let data = {}
          data.id = key,
            data.label = template[key]
          // 初始化saveInfo.accountValue
          this.saveInfo.accountValue[key] = ''
          this.accountTemplateList.push(data)
        }
      }
    },
    checkBoxItemChange(e, key) {
      if (e && key === 'dictIdentityPicFront') {
        this.config.push('dictCustomerName')
        this.config.push('dictIdentityNumber')
        this.configList[3].disabled = true
        this.configList[4].disabled = true

      } else if (!e && key === 'dictIdentityPicFront') {

        for (let index = this.config.length - 1; index >= 0; index--) {
          const item = this.config[index];
          // console.log(item)
          // console.log(index)
          if (item === 'dictIdentityNumber' || item === 'dictCustomerName') {
            // console.log(item)
            // console.log(index)
            this.config.splice(index, 1)
          }

        }
        this.configList[3].disabled = false
        this.configList[4].disabled = false
      }
    },
    reRender() {
      this.$forceUpdate()
    },
    downloadTemplate() {
      let url = `https://imgsd.1688iot.vip/%E5%AF%BC%E5%85%A5%E7%89%A9%E6%B5%81%E4%BF%A1%E6%81%AF%E6%A8%A1%E6%9D%BF.xls`
      window.location.href = url
    },
    async getFile(fileList) {
      if (fileList !== '') {
        return false
      } else {
        //console.log(fileList)

        this.fileList.excel = this.$refs.key.files[0]
        if (this.$refs.key.files[0] != null) {
          this.fileName = this.$refs.key.files[0].name
        }
      }
      let a = await importChangeExcel({
        file: this.fileList.excel
      })

      if (a.code == 10000) {
        this.$message.success("处理成功！")
        this.loading = false
      } else {
        this.$message.error("处理失败！")
      }


    }
  }
};
</script>
<style scoped lang="scss">
.el-popper[x-placement^=bottom] {
  margin-right: -31px;
  box-shadow: 0px 0px 10px #888888;
  margin-left: 6px;

  .operation {
    border: 0;
    outline: none;
    display: block;
    text-align: center;
    margin: 0;
  }
}

.el-popper[x-placement^=top] {
  box-shadow: 0px 0px 10px #888888;
  margin-left: 6px;
  margin-right: -31px;

  button {
    display: block;
  }

  .operation {
    border: 0;
    outline: none;
    display: block;
    text-align: center;
    margin: 0;
  }
}

.drawer_form {
  padding: 50px;
  overflow-y: auto;

  .custom_drawer_content {
    width: 100%;
  }
}

/deep/ .el-drawer.ttb {
  width: 500px;
  left: 50%;
  margin-left: -250px;
  /* right:50%; */
}

// .notice_drawer_form {
//   width: 100%;
// }
.recentAdd li {
  list-style: none;
  float: left;
  margin-right: 5px;
  line-height: 15px;
}
</style>
<style>
.el-drawer.ttb {
  width: 800px;
  left: 50%;
  margin-left: -400px;
  /* right:50%; */
}
</style>
